package com.zyz.zchat;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.*;
import java.util.HashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ChatManager {
    ServerSocket listener;
    public static final int listenPort=2022;
    ExecutorService listenService;
    Future listenStatus;
    HashMap<InetAddress,Chat> chats;
    ChatManager()
    {
        try {
            listener=new ServerSocket(listenPort);
            chats=new HashMap<>();
            listenService= Executors.newSingleThreadExecutor();
            listenStatus= listenService.submit(new Thread(()-> {
                while (true)
                    listen();
            }));

        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("监听失败");
        }
    }
    void addChat(Chat c)
    {
        if(c!=null)
            chats.put(c.dest,c);
    }
    void listen()
    {
            try(Socket peer = listener.accept();)
            {
                    InetAddress remoteAddr = peer.getInetAddress();
                    ObjectInputStream in = new ObjectInputStream(peer.getInputStream());
                    Message m = (Message) in.readObject();
                    in.close();
                    if(!peer.isClosed())
                        peer.close();
                if (!chats.containsKey(remoteAddr))
                            addChat(new Chat(remoteAddr));
                        chats.get(remoteAddr).receiveMessage(m);
            }
            catch (ClassNotFoundException | IOException e)
            {
                e.printStackTrace();
            }
    }

    public static void main(String[] args) {
        InetAddress addr= null;
        try {
            addr = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        ChatManager r=new ChatManager();
        Chat c= null;
        try {
            c = new Chat(addr);
        } catch (IOException e) {
            e.printStackTrace();
        }
        assert c != null;
        r.chats.put(c.peer.getInetAddress(),c);

        c.sendMessage("?");
        c.sendMessage("?");
        System.out.println(c);

    }
}
